package com.example.controller;


import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.result.Result;
import com.example.entity.hz.MOCTA;
import com.example.entity.mysql.Resource;
import com.example.entity.mysql.Resourcegroup;
import com.example.entity.mysql.Workresource;
import com.example.entity.vo.hzView.*;
import com.example.entity.yifei.*;
import com.example.enums.MOCStatusEnum;
import com.example.enums.MouldStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.mapper.hzViewSync.HzViewSyncMapper;
import com.example.mapper.pc.ProductprocessresourceMapper;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.ResourcegroupMapper;
import com.example.service.*;
import com.example.service.pc.ProductprocessresourceService;
import com.example.service.pc.ResourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.service.pc.WorkresourceService;
import com.example.untils.BeanUtils;
import com.example.untils.LanguageConversionUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import com.github.houbb.opencc4j.core.impl.ZhConvertBootstrap;
import com.github.houbb.opencc4j.support.segment.impl.Segments;
import com.github.houbb.opencc4j.util.ZhTwConverterUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lan
 * @since 2024-11-13
 */
@RestController
@RequestMapping("/api/mocta2")
public class Mocta2Controller {

    @Autowired
    private ViewsynclogService viewsynclogService;
    @Autowired
    private WorkresourceService workresourceService;
    @Autowired
    private HzViewSyncMapper hzViewSyncMapper;
    @Autowired
    private ResourcegroupMapper resourcegroupMapper;
    @Autowired
    private ResourcegroupService resourcegroupService;
    @Autowired
    private ProductprocessresourceService productprocessresourceService;
    @Autowired
    private ProductprocessresourceMapper productprocessresourceMapper;
    @Autowired
    private TablesynclogService tablesynclogService;
    @Autowired
    private InvmbMapper invmbMapper;
    @Autowired
    private InvmbService invmbService;
    @Autowired
    private CmsmeMapper cmsmeMapper;
    @Autowired
    private CmsmvMapper cmsmvMapper;
    @Autowired
    private CmsmeService  cmsmeService;
    @Autowired
    private CmsmvService cmsmvService;
    @Autowired
    private CmsmcMapper cmsmcMapper;
    @Autowired
    private CmsmcService cmsmcService;
    @Autowired
    private BommfMapper bommfMapper;
    @Autowired
    private BommfService bommfService;
    @Autowired
    private CmsmdService cmsmdService;
    @Autowired
    private CmsmdMapper cmsmdMapper;
    @Autowired
    private PurmaService purmaService;
    @Autowired
    private PurmaMapper purmaMapper;
    @Autowired
    private BommeMapper bommeMapper;
    @Autowired
    private BommeService bommeService;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private CoptdMapper coptdMapper;
    @Autowired
    private CoptdService coptdService;
    @Autowired
    private PurcdMapper purcdMapper;
    @Autowired
    private PurcdService purcdService;
    @Autowired
    private PurtdMapper purtdMapper;
    @Autowired
    private PurtdService purtdService;
    @Autowired
    private MoctaMapper moctaMapper;
    @Autowired
    private MoctaService moctaService;
    @Autowired
    private SfctaMapper sfctaMapper;
    @Autowired
    private SfctaService sfctaService;
    @Autowired
    private MoctbService moctbService;
    @Autowired
    private MoctbMapper moctbMapper;
    @Autowired
    private MoctyService moctyService;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private Mocta2Mapper mocta2Mapper;
    @Autowired
    private Mocta2Service mocta2Service;
    @Autowired
    private Moctb2Mapper moctb2Mapper;
    @Autowired
    private Moctb2Service moctb2Service;
    @Autowired
    private MocteMapper mocteMapper;
    @Autowired
    private MocteService mocteService;
    @Autowired
    private MoctgMapper moctgMapper;
    @Autowired
    private MoctgService moctgService;

    @ApiOperation("同步模具其他信息")
    @PostMapping("syncMouldOtherInfo")
    @DSTransactional
    public Result syncMouldOtherInfo() {
        List<HzResourceView> list = hzViewSyncMapper.getResource();
        Map<String, HzResourceView> map = new HashMap<>();
        for(HzResourceView t : list) {
            map.put(t.getDeviceId().trim(), t);
        }

        List<Resource> resources = resourceMapper.selectList(null);
        for(Resource resource : resources) {
            HzResourceView view = map.get(resource.getDeviceid().trim());
            if(view == null) continue;
            BeanUtils.copyPropertiesIgnoreCase(view, resource);
//            resource.set
            resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, resource.getDeviceid()));
        }
        return Result.success();
    }

    @ApiOperation("同步模具存储位置")
    @PostMapping("syncResourceStorageLocation")
    @DSTransactional
    public Result test01() {

        List<HzResourceView> list = hzViewSyncMapper.getResource();
        Map<String, String> map = new HashMap<>();
        for(HzResourceView t : list) {
            map.put(t.getDeviceId().trim(), t.getStorageLocation().trim());
        }

        List<Resource> resources = resourceMapper.selectList(null);
        for(Resource resource : resources) {
            String s = map.get(resource.getDeviceid().trim());
            if(s == null) continue;
            resource.setStorageLocation(s);
            resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, resource.getDeviceid()));
        }
        return Result.success();
    }

    @ApiOperation("临时同步一次")
    @PostMapping("syncOneTimeSFCTAMOCTAMOCTB")
    @DSTransactional
    public Result test02() {

        System.out.println("合并的工单MOCTAMERGE Sync....." + TimeUtils.getFullNowTime());
        Tablesynclog moctaMergeLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTAMERGE"));
        List<HzMoctaView> viewList = null;
        if(moctaMergeLog == null || StringUtils.isEmpty(moctaMergeLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            viewList = hzViewSyncMapper.hzMoctaMergeViewList(null);
        }else{
            viewList = hzViewSyncMapper.hzMoctaMergeViewList(moctaMergeLog.getLastsynctime());
        }
        if(viewList != null && viewList.size() > 0) {
            List<Cmsmv> cmsmvList = cmsmvMapper.selectList(null);
            Map<String, String> cmsmvMap = new HashMap<>();
            for(Cmsmv cmsmv : cmsmvList) {
                cmsmvMap.put(cmsmv.getMv002().trim(), cmsmv.getMv001().trim());
            }

            List<String> moctaKeyList = moctaMapper.getmoctaKeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : moctaKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzMoctaView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < viewList.size(); i++) {
                viewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(viewList.get(i)));
            }
            for(HzMoctaView item : viewList) {
                viewMap.put(item.getTA001().trim() + "^" + item.getTA002().trim(), item);
                viewSet.add(item.getTA001().trim() + "^" + item.getTA002().trim());
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
            }
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);

            List<MOCTA> insMoctaList = new ArrayList<>();
            List<Mocty> mocties = new ArrayList<>();
            List<Workresource> workresources = new ArrayList<>();
            for(String t : cp) {  // 插入VIEW中多的
                HzMoctaView view = viewMap.get(t);
                MOCTA mocta = new MOCTA();
                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
                String s = cmsmvMap.get(mocta.getTA041());
                if(s != null) mocta.setTA041(s);
                mocta.setCREATOR("ERP");
                mocta.setCREATE_DATE(TimeUtils.getNowTime());
                mocta.setUDF01(view.getInvrt_name());  //
                mocta.setUDF02(view.getProcessroute()); //
                mocta.setUDF03(view.getProcessid());   // 工艺ID
                mocta.setUDF04(view.getInv_no());   // 产成品品号
                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
                mocta.setUDF06(view.getCustomName());
                insMoctaList.add(mocta);

                // 隨便去mocty中抓一個
                Mocty pp = moctyMapper.oneMocty(view.getTA001(), view.getTA002());

                Mocty mocty2 = new Mocty();
                mocty2.setTy001(view.getTA001().trim());
                mocty2.setTy002(view.getTA002().trim());
                mocty2.setTy003(mocty2.getTy001() + mocty2.getTy002());   // 区分是哪个
                mocty2.setTy004(view.getTA015().doubleValue());
                mocty2.setTy009(pp.getTy009());
                mocty2.setTy019(pp.getTy019());
                mocty2.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                mocty2.setUdf11(mocty2.getTy001());
                mocty2.setUdf12(mocty2.getTy002());
                mocty2.setUdf05(mocty2.getTy001() + mocty2.getTy002());
                mocties.add(mocty2);

                List<Workresource> list3 = workresourceService.list(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, pp.getUdf05()));
                if(list3 != null && list3.size() > 0) {  // 将WorkResource补录
                    for(Workresource t1 : list3) {
                        Workresource workresource = new Workresource();
                        BeanUtils.copyPropertiesIgnoreCase(t1, workresource);
                        workresource.setWorkResourceId(UUID.randomUUID().toString());
                        workresource.setProductLineId(mocty2.getTy001() + mocty2.getTy002());
                        workresource.setCreateTime(TimeUtils.getFullNowTime());
                        workresources.add(workresource);
                    }
                }

            }

            // 批量插入
            moctaService.saveBatch(insMoctaList);
            moctyService.saveBatch(mocties);
            workresourceService.saveBatch(workresources);
            // 批量更新
            cp = new HashSet<>(originSet);
            cp.retainAll(viewSet);
            for(String t : cp) {
                MOCTA mocta = new MOCTA();
                HzMoctaView view = viewMap.get(t);
                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
                mocta.setUDF01(view.getInvrt_name());  //
                mocta.setUDF02(view.getProcessroute()); //
                mocta.setUDF03(view.getProcessid());   // 工艺ID
                mocta.setUDF04(view.getInv_no());   // 产成品品号
                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
                mocta.setUDF06(view.getCustomName());
                String s = cmsmvMap.get(mocta.getTA041());
                if(s != null) mocta.setTA041(s);
                mocta.setMODIFIER("ERP");
                mocta.setMODI_DATE(TimeUtils.getNowTime());
                moctaService.update(mocta, new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, view.getTA001()).eq(MOCTA::getTA002, view.getTA002()));

                Mocty mocty = new Mocty();
                mocty.setTy004(mocta.getTA015().doubleValue());
                moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, view.getTA001().trim() + view.getTA002().trim()));
            }
            if(moctaMergeLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("MOCTAMERGE");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTAMERGE"));
            }
        }
        System.out.println("合并的工单 end....." + TimeUtils.getFullNowTime());


        return Result.success();
    }

//    @ApiOperation("moctatest 无分页")
//    @PostMapping("moctatest")
//    public Result test01(@RequestBody String str) {
//        System.out.println("原MOCTA Sync....." + TimeUtils.getFullNowTime());
//        List<HzMoctaView> moctaViewList = hzViewSyncMapper.hzMoctaViewListTest(str);
//        if (moctaViewList != null && moctaViewList.size() > 0) {
//
//            List<Cmsmv> cmsmvList = cmsmvMapper.selectList(null);
//            Map<String, String> cmsmvMap = new HashMap<>();
//            for (Cmsmv cmsmv : cmsmvList) {
//                cmsmvMap.put(cmsmv.getMv002().trim(), cmsmv.getMv001().trim());
//            }
//
//            List<String> moctaKeyList = moctaMapper.getmocta2KeyList();
//            Set<String> originSet = new HashSet<>();
//            for (String t : moctaKeyList) originSet.add(t);
//
//            Set<String> viewSet = new HashSet<>();
//            Map<String, HzMoctaView> viewMap = new HashMap<>();
//            String lastTime = "";
//            for (int i = 0; i < moctaViewList.size(); i++) {
//                moctaViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(moctaViewList.get(i)));
//            }
//            for (HzMoctaView item : moctaViewList) {
//                viewMap.put(item.getTA001().trim() + "^" + item.getTA002().trim(), item);
//                viewSet.add(item.getTA001().trim() + "^" + item.getTA002().trim());
//                if (lastTime == "") lastTime = item.getModified_time();
//                else {
//                    if (lastTime.compareTo(item.getModified_time()) < 0) {
//                        lastTime = item.getModified_time();
//                    }
//                }
//            }
//            Set<String> cp = new HashSet<>(viewSet);
//            cp.removeAll(originSet);
//            List<Mocta2> insMoctaList = new ArrayList<>();
//            List<Mocty> insMoctyList = new ArrayList<>();
//            List<Workresource> insWorkresourceList = new ArrayList<>();
//            // 存一下每一个资源组的工作时间
//            Map<String, BigDecimal> hzCmsmxMap = new HashMap<>();
//            List<HzCmsmxView> hzCmsmxViewList = hzViewSyncMapper.hzCmsmxViewList();
//            for (HzCmsmxView t : hzCmsmxViewList) {
//                if (t.getResourceType().equals(1)) {
//                    hzCmsmxMap.put(t.getMX009().trim(), t.getMX004());
//                } else if (t.getResourceType().equals(2)) {
//                    hzCmsmxMap.put(t.getMX009().trim(), t.getMX004());
//                }
//            }
//
//            for (String t : cp) {  // 插入VIEW中多的
//                HzMoctaView view = viewMap.get(t);
//                Mocta2 mocta = new Mocta2();
//                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
//                String s = cmsmvMap.get(mocta.getTA041());
//                if (s != null) mocta.setTA041(s);
//                mocta.setCREATOR("ERP");
//                mocta.setCREATE_DATE(TimeUtils.getNowTime());
//                mocta.setUDF01(view.getInvrt_name());  //
//                mocta.setUDF02(view.getProcessroute()); //
//                mocta.setUDF03(view.getProcessid());   // 工艺ID
//                mocta.setUDF04(view.getInv_no());   // 产成品品号
//                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
//                mocta.setUDF06(view.getCustomName());
//                insMoctaList.add(mocta);
//
//
//                String uuid = UUID.randomUUID().toString();
//                int productNumPerDay = 0;
//                // 如果有产能的，需要算机器每日的产能。   如果没有的话，则直接排满
//                SFCTA sfcta = sfctaMapper.selectOne(new LambdaQueryWrapper<SFCTA>()
//                        .eq(SFCTA::getTA001, view.getTA001().trim()).eq(SFCTA::getTA002, view.getTA025TA006().trim()));
//                List<Productprocessresource> list = productprocessresourceMapper.selPPRListHzVersion(
//                        new GetProductLineMachineHzViewDto(mocta.getTA006(), sfcta.getTA003(), sfcta.getTA004(), mocta.getUDF01(),
//                                mocta.getUDF02(), mocta.getTA021(), mocta.getUDF04(), null, 1));
//                boolean flag = false;
//                Integer jutiId = null;
//                for (Productprocessresource productprocessresource : list) {
//                    if ("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
//                        // 如果是装配车间的话，不需要填充 1和2 之外的东西
//                        if (!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
//                            continue;
//                        }
//                    }
//                    if (productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {   // 看一下这个工单能不能选到具体的 生产线/设备
//                        List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
//                        if (idList == null || idList.size() == 0) continue;
//                        if (idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
//                            jutiId = idList.get(0);
//                        }
//                        BigDecimal hours = hzCmsmxMap.get(productprocessresource.getResourceGroupNO().trim());
//                        double v = hours.doubleValue();
//                        productNumPerDay = (int) Math.floor(v * 3600 / productprocessresource.getBeat());  // 计算日产量
//                        flag = true;
//                        break;
//                    }
//                }
//                if (!flag) {  // 如果没有绑定生产线/设备
//
//                    Mocty mocty = new Mocty();
//                    mocty.setCreator("ERP");
//                    mocty.setCreateDate(TimeUtils.getNowTime());
//                    mocty.setTy001(view.getTA001().trim());
//                    mocty.setTy002(view.getTA025TA006().trim());
//                    mocty.setTy003(view.getTA009().trim());
//                    mocty.setTy004(view.getTA015().doubleValue());
//                    mocty.setTy009("****");
//                    mocty.setTy019(sfcta.getTA003());  // 工序
//                    mocty.setUdf05(UUID.randomUUID().toString());
//                    mocty.setUdf06(uuid);
//                    mocty.setUdf11(view.getTA001().trim());  // 原MOCTA TA001
//                    mocty.setUdf12(view.getTA002().trim());  // 原MOCTA TA002
//                    mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
//                    mocty.setUdf04("转入参数: " + view.toString());
//                    insMoctyList.add(mocty);
//                    for (Productprocessresource productprocessresource : list) {
//                        if ("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
//                            // 如果是装配车间的话，不需要填充 1和2 之外的东西
//                            if (!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
//                                continue;
//                            }
//                        }
//                        Workresource workresource = new Workresource();
//                        workresource.setWorkResourceId(UUID.randomUUID().toString());
//                        workresource.setWorkSingle(mocta.getTA001());
//                        workresource.setWorkNo(mocta.getTA025().trim() + "-" + mocta.getTA006().trim());
//                        workresource.setProcessNo(sfcta.getTA003());
//                        workresource.setProcessId(sfcta.getTA004());
//                        workresource.setResourceGroupId(productprocessresource.getResourceGroupId());
//
//                        if (productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
//                            List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
//                            if (idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
//                                workresource.setResourceId(idList.get(0));
//                            }
//                        } else {
//                            List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), null);
//                            if (idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
//                                workresource.setResourceId(idList.get(0));
//                            }
//                        }
//                        workresource.setDate(mocta.getTA009());
//                        workresource.setBeat(productprocessresource.getBeat());
//                        workresource.setQuota(productprocessresource.getQuota());
//                        workresource.setCreator("ERP");
//                        workresource.setCreateTime(TimeUtils.getFullNowTime());
//                        workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
//                        insWorkresourceList.add(workresource);
//                    }
//                } else {
//                    int day = (int) Math.ceil(mocta.getTA015().doubleValue() / productNumPerDay);
//                    int sum = 0;
//                    // 需要查看当天是否为休息日，如果是的话，则需要往后排
//                    for (int i = 0; i < day; i++) {
//                        Mocty mocty = new Mocty();
//                        mocty.setCreator("ERP");
//                        mocty.setCreateDate(TimeUtils.getNowTime());
//                        mocty.setTy001(view.getTA001().trim());
//                        mocty.setTy002(view.getTA025TA006().trim());
//                        mocty.setTy003(TimeUtils.addOrSubtract(view.getTA009().trim(), i));
//                        if (i == day - 1) mocty.setTy004(mocta.getTA015().doubleValue() - sum);
//                        else {
//                            sum += productNumPerDay;
//                            mocty.setTy004(new Double(productNumPerDay));
//                        }
//                        if (jutiId == null) {
//                            mocty.setTy009("****");
//                            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
//                        } else {
//                            mocty.setTy009(jutiId.toString());
//                            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
//                        }
//                        mocty.setTy019(sfcta.getTA003());  // 工序
//                        mocty.setUdf05(UUID.randomUUID().toString());
//                        mocty.setUdf06(uuid);
//                        mocty.setUdf11(view.getTA001().trim());  // 原MOCTA TA001
//                        mocty.setUdf12(view.getTA002().trim());  // 原MOCTA TA002
//                        mocty.setUdf04("转入参数: " + view.toString());
//                        insMoctyList.add(mocty);
//                        for (Productprocessresource productprocessresource : list) {
//                            if ("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
//                                // 如果是装配车间的话，不需要填充 1和2 之外的东西
//                                if (!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
//                                    continue;
//                                }
//                            }
//                            Workresource workresource = new Workresource();
//                            workresource.setWorkResourceId(UUID.randomUUID().toString());
//                            workresource.setWorkSingle(mocta.getTA001());
//                            workresource.setWorkNo(mocta.getTA025().trim() + "-" + mocta.getTA006().trim());
//                            workresource.setProcessNo(sfcta.getTA003());
//                            workresource.setProcessId(sfcta.getTA004());
//                            workresource.setResourceGroupId(productprocessresource.getResourceGroupId());
//
//                            if (productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
//                                List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
//                                if (idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
//                                    workresource.setResourceId(idList.get(0));
//                                }
//                            } else {
//                                List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), null);
//                                if (idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
//                                    workresource.setResourceId(idList.get(0));
//                                }
//                            }
//                            workresource.setDate(TimeUtils.addOrSubtract(mocta.getTA009().trim(), i));
//                            workresource.setBeat(productprocessresource.getBeat());
//                            workresource.setQuota(productprocessresource.getQuota());
//                            workresource.setCreator("ERP");
//                            workresource.setCreateTime(TimeUtils.getFullNowTime());
//                            workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
//                            insWorkresourceList.add(workresource);
//                        }
//                    }
//                }
//            }
//            System.out.println();
//        }
//
//        return Result.success();
//    }

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @ApiOperation("MOCTBtong bu")
    @PostMapping("MOCTBtongBu")
    @DSTransactional
    public Result test03() {

        System.out.println("MOCTBSync....." + TimeUtils.getFullNowTime());
        Tablesynclog moctbLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTB"));
        List<HzMoctbView> moctbViewList = null;
        if(moctbLog == null || StringUtils.isEmpty(moctbLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            moctbViewList = hzViewSyncMapper.hzMoctbViewList(null);
        }else{
            moctbViewList = hzViewSyncMapper.hzMoctbViewList(moctbLog.getLastsynctime());
        }
        if(moctbViewList != null && moctbViewList.size() > 0) {
            System.out.println("MOCTB 取数据" + TimeUtils.getFullNowTime());
            List<String> moctbKeyList = moctbMapper.getmoctbKeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : moctbKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzMoctbView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < moctbViewList.size(); i++) {
                moctbViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(moctbViewList.get(i)));
            }
            for(HzMoctbView item : moctbViewList) {
                if(StringUtils.isEmpty(item.getTB001()) || StringUtils.isEmpty(item.getTB002()) || item.getLINE_NO() == null) continue;
                viewMap.put(item.getTB001().trim() + "^" + item.getTB002().trim() + "^" + item.getLINE_NO().toString().trim(), item);
                viewSet.add(item.getTB001().trim() + "^" + item.getTB002().trim() + "^" + item.getLINE_NO().toString().trim());
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
            }
            System.out.println("MOCTB 新增数据" + TimeUtils.getFullNowTime());
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);
            List<Moctb2> insMoctbList = new ArrayList<>();
//            Map<String, Moctb> insMoctbMergeMap = new HashMap<>();
            for(String t : cp) {  // 插入VIEW中多的
                HzMoctbView view = viewMap.get(t);
                if(view.getMATTYPE() == null) view.setMATTYPE("");
                if(view.getBommat_id() == null) view.setBommat_id("");
                Moctb2 moctb = new Moctb2();
                BeanUtils.copyPropertiesIgnoreCase(view, moctb);
                moctb.setUdf03(view.getLINE_NO().toString());
                moctb.setUdf04(view.getMATTYPE());
                moctb.setUdf05(view.getBommat_id());
                moctb.setUdf07(view.getHasAltInv());  //
                moctb.setUdf08(view.getAlter_Rate()); //
                moctb.setCreator("ERP");
                moctb.setCreateDate(TimeUtils.getNowTime());

                StringBuffer sb = new StringBuffer();
                sb.append(moctb.getTb001().trim()).append(view.getTA025TA006().trim()).append(view.getTB006().trim())
                        .append(view.getTB003().trim());
                sb.append(view.getMATTYPE().trim());
                sb.append(view.getBommat_id().trim());

//                Moctb x = insMoctbMergeMap.get(sb.toString());
                Moctb x = moctbMapper.selX(moctb.getTb001(), view.getTA025TA006(), view.getTB006(), view.getTB003(),
                        view.getMATTYPE(), view.getBommat_id());
                Boolean f = false;
                if(x == null) {
                    f = true;
                    x = new Moctb();
                    BeanUtils.copyPropertiesIgnoreCase(moctb, x);
                    x.setTb002(view.getTA025TA006());
                }
                if(!f) {
                    x.setTb004(view.getTB004() + x.getTb004());
                    x.setTb005(view.getTB005() + x.getTb005());
                    moctbService.update(x, new LambdaQueryWrapper<Moctb>()
                            .eq(Moctb::getTb001, x.getTb001())
                            .eq(Moctb::getTb002, x.getTb002())
                            .eq(Moctb::getTb003, x.getTb003())
                            .eq(Moctb::getUdf04, x.getUdf04())
                            .eq(Moctb::getUdf05, x.getUdf05()));
                }else{
                    moctbService.save(x);
                }
//                insMoctbMergeMap.put(sb.toString(), x);

                insMoctbList.add(moctb);
            }
            // 批量插入
            moctb2Service.saveBatch(insMoctbList);
//            List<Moctb> insMoctb = new ArrayList<>();
//            for (Map.Entry<String, Moctb> entry : insMoctbMergeMap.entrySet()) {
//                System.out.println("Key: " + entry.getKey() + ", Value: " +);
//                insMoctb.add(entry.getValue());
//            }
//            moctbService.saveBatch(insMoctb);
            System.out.println("MOCTB 更新数据" + TimeUtils.getFullNowTime());
            // 批量更新
            cp = new HashSet<>(viewSet);
            cp.retainAll(originSet);

            for(String t : cp) {
                HzMoctbView view = viewMap.get(t);
                if(view.getMATTYPE() == null) view.setMATTYPE("");
                if(view.getBommat_id() == null) view.setBommat_id("");
                Moctb2 moctb = new Moctb2();
                BeanUtils.copyPropertiesIgnoreCase(view, moctb);
                moctb.setUdf03(view.getLINE_NO().toString());
                moctb.setUdf04(view.getMATTYPE());
                moctb.setUdf05(view.getBommat_id());
                moctb.setUdf07(view.getHasAltInv());  //
                moctb.setUdf08(view.getAlter_Rate()); //
                moctb.setModifier("ERP"); moctb.setModiDate(TimeUtils.getNowTime());
                // 這個是 MOCTB
                Moctb2 oldMoctb2 = moctb2Mapper.selectOne(new LambdaQueryWrapper<Moctb2>()
                        .eq(Moctb2::getTb001, view.getTB001())
                        .eq(Moctb2::getTb002, view.getTB002())
                        .eq(Moctb2::getUdf03, view.getLINE_NO().toString().trim()));

                if(view.getTB006().trim().equals(oldMoctb2.getTb006())) {
                    Moctb x = moctbMapper.selX(moctb.getTb001(), view.getTA025TA006(), view.getTB006(), view.getTB003(),
                            view.getMATTYPE(), view.getBommat_id());
                    x.setTb004(view.getTB004() + x.getTb004() - oldMoctb2.getTb004());
                    x.setTb005(view.getTB005() + x.getTb005() - oldMoctb2.getTb005());

                    moctbService.update(x, new LambdaQueryWrapper<Moctb>()
                            .eq(Moctb::getTb001, x.getTb001())
                            .eq(Moctb::getTb002, x.getTb002())
                            .eq(Moctb::getTb003, x.getTb003())
                            .eq(Moctb::getUdf04, x.getUdf04())
                            .eq(Moctb::getUdf05, x.getUdf05()));

                    moctb2Service.update(moctb, new LambdaQueryWrapper<Moctb2>()
                            .eq(Moctb2::getTb001, view.getTB001())
                            .eq(Moctb2::getTb002, view.getTB002())
                            .eq(Moctb2::getUdf03, view.getLINE_NO().toString().trim()));
                }else{
                    Moctb x = moctbMapper.selX(moctb.getTb001(), view.getTA025TA006(), oldMoctb2.getTb006(), oldMoctb2.getTb003(),
                            oldMoctb2.getUdf04(), oldMoctb2.getUdf05());
                    x.setTb004(view.getTB004() - oldMoctb2.getTb004());
                    x.setTb005(view.getTB005() - oldMoctb2.getTb005());
                    // 將原來的減去
                    moctbService.update(x, new LambdaQueryWrapper<Moctb>()
                            .eq(Moctb::getTb001, x.getTb001())
                            .eq(Moctb::getTb002, x.getTb002())
                            .eq(Moctb::getTb003, x.getTb003())
                            .eq(Moctb::getUdf04, x.getUdf04())
                            .eq(Moctb::getUdf05, x.getUdf05()));

                    moctb2Service.update(moctb, new LambdaQueryWrapper<Moctb2>()
                            .eq(Moctb2::getTb001, view.getTB001())
                            .eq(Moctb2::getTb002, view.getTB002())
                            .eq(Moctb2::getUdf03, view.getLINE_NO().toString().trim()));

                    // 然后再判斷之前的有沒有，沒有的話。沒有就新增。不然就修改
                    x = moctbMapper.selX(moctb.getTb001(), view.getTA025TA006(), view.getTB006(), view.getTB003(),
                            view.getMATTYPE(), view.getBommat_id());
                    Boolean f = false;
                    if(x == null) {
                        f = true;
                        x = new Moctb();
                        BeanUtils.copyPropertiesIgnoreCase(moctb, x);
                        x.setTb002(view.getTA025TA006());
                    }
                    if(!f) {
                        x.setTb004(view.getTB004() + x.getTb004());
                        x.setTb005(view.getTB005() + x.getTb005());
                        moctbService.update(x, new LambdaQueryWrapper<Moctb>()
                                .eq(Moctb::getTb001, x.getTb001())
                                .eq(Moctb::getTb002, x.getTb002())
                                .eq(Moctb::getTb003, x.getTb003())
                                .eq(Moctb::getUdf04, x.getUdf04())
                                .eq(Moctb::getUdf05, x.getUdf05()));
                    }else{
                        moctbService.save(x);
                    }
                }
            }

            if(moctbLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("MOCTB");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTB"));
            }

        }
        System.out.println("MOCTB end....." + TimeUtils.getFullNowTime());

        return Result.success();
    }

    @ApiOperation("MOCTGtong bu")
    @PostMapping("moctgTest")
    @DSTransactional
    public Result moctgTest() {
        System.out.println("moctg ViewSync start.........");
        List<HzMoctgView> hzMoctgViewList = null;
        Tablesynclog hzMoctgLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTG"));
        if(hzMoctgLog == null || StringUtils.isEmpty(hzMoctgLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            hzMoctgViewList = hzViewSyncMapper.hzMoctgViewList(null);
        }else{
            hzMoctgViewList = hzViewSyncMapper.hzMoctgViewList(hzMoctgLog.getLastsynctime());
        }
        if(hzMoctgViewList != null && hzMoctgViewList.size() > 0) {

            List<String> moctgKeyList = moctgMapper.getMoctgKeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : moctgKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzMoctgView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < hzMoctgViewList.size(); i++) {
                hzMoctgViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(hzMoctgViewList.get(i)));
            }
            for(HzMoctgView item : hzMoctgViewList) {
                viewMap.put(item.getTG001().trim() + "^" + item.getTG002().trim() + "^" + item.getTG003().trim(), item);
                viewSet.add(item.getTG001().trim() + "^" + item.getTG002().trim() + "^" + item.getTG003().trim());
                if(lastTime == "") lastTime = item.getModified_Time();
                else {
                    if(lastTime.compareTo(item.getModified_Time()) < 0) {
                        lastTime = item.getModified_Time();
                    }
                }
            }
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);

            List<Moctg> insMoctgList = new ArrayList<>();
            for(String t : cp) {  // 插入VIEW中多的
                HzMoctgView view = viewMap.get(t);
                Moctg moctg = new Moctg();
                BeanUtils.copyPropertiesIgnoreCase(view, moctg);
                insMoctgList.add(moctg);
            }
            // 批量插入
            moctgService.saveBatch(insMoctgList);
            // 批量更新
            cp = new HashSet<>(originSet);
            cp.retainAll(viewSet);
            for(String t : cp) {
                HzMoctgView view = viewMap.get(t);
                Moctg moctg = new Moctg();
                BeanUtils.copyPropertiesIgnoreCase(view, moctg);
                moctgMapper.update(moctg, new LambdaQueryWrapper<Moctg>().eq(Moctg::getTg001, view.getTG001())
                        .eq(Moctg::getTg002, view.getTG002()).eq(Moctg::getTg003, view.getTG003()));
            }
            if(hzMoctgLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("MOCTG");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTG"));
            }
        }
        System.out.println("MOCTG end....." + TimeUtils.getFullNowTime());


        return Result.success();
    }

    @ApiOperation("MOCTEEEEtong bu")
    @PostMapping("mocteTest")
    @DSTransactional
    public Result mocteTest() {
        System.out.println("mocte ViewSync start.........");
        List<HzMocteView> hzMocteViewList = null;
        Tablesynclog hzMocteLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTE"));
        if(hzMocteLog == null || StringUtils.isEmpty(hzMocteLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            hzMocteViewList = hzViewSyncMapper.hzMocteViewList(null);
        }else{
            hzMocteViewList = hzViewSyncMapper.hzMocteViewList(hzMocteLog.getLastsynctime());
        }
        if(hzMocteViewList != null && hzMocteViewList.size() > 0) {

            List<String> mocteKeyList = mocteMapper.getMocteKeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : mocteKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzMocteView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < hzMocteViewList.size(); i++) {
                hzMocteViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(hzMocteViewList.get(i)));
            }
            for(HzMocteView item : hzMocteViewList) {
                viewMap.put(item.getTE001().trim() + "^" + item.getTE002().trim() + "^" + item.getTE003().trim(), item);
                viewSet.add(item.getTE001().trim() + "^" + item.getTE002().trim() + "^" + item.getTE003().trim());
                if(lastTime == "") lastTime = item.getModified_Time();
                else {
                    if(lastTime.compareTo(item.getModified_Time()) < 0) {
                        lastTime = item.getModified_Time();
                    }
                }
            }
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);

            List<Mocte> insMocteList = new ArrayList<>();
            for(String t : cp) {  // 插入VIEW中多的
                HzMocteView view = viewMap.get(t);
                Mocte mocte = new Mocte();
                BeanUtils.copyPropertiesIgnoreCase(view, mocte);
                insMocteList.add(mocte);
            }
            // 批量插入
            mocteService.saveBatch(insMocteList);
            // 批量更新
            cp = new HashSet<>(originSet);
            cp.retainAll(viewSet);
            for(String t : cp) {
                HzMocteView view = viewMap.get(t);
                Mocte mocte = new Mocte();
                BeanUtils.copyPropertiesIgnoreCase(view, mocte);
                mocteMapper.update(mocte, new LambdaQueryWrapper<Mocte>().eq(Mocte::getTe001, view.getTE001())
                        .eq(Mocte::getTe002, view.getTE002()).eq(Mocte::getTe003, view.getTE003()));
            }
            if(hzMocteLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("MOCTE");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTE"));
            }
        }
        System.out.println("MOCTE end....." + TimeUtils.getFullNowTime());

        return Result.success();
    }

    @ApiOperation("resourceGroup_ResourceViewSync tong bu")
    @PostMapping("resourceGroup_ResourceViewSync")
    @DSTransactional
    public void resourceGroup_ResourceViewSync() {
        System.out.println("resourceGroup_ResourceViewSync start.........");
        List<HzResourceGroupView> resourceGroupViewList = null;
        Tablesynclog resourcegroupLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "resourcegroup"));
        if(resourcegroupLog == null || StringUtils.isEmpty(resourcegroupLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            resourceGroupViewList = hzViewSyncMapper.hzResourceGroupViewList(null);
        }else{
            resourceGroupViewList = hzViewSyncMapper.hzResourceGroupViewList(resourcegroupLog.getLastsynctime());
        }

        if(resourceGroupViewList != null && resourceGroupViewList.size() > 0) {
            Set<String> groupNoSet = new HashSet<>();   // 视图中的组编号
            Map<String, Integer> groupNoMap = new HashMap<>();  // 视图中的组编号对应的 -- 1，2，3，4
            Map<String, String> groupNoNameMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < resourceGroupViewList.size(); i++) {
                resourceGroupViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(resourceGroupViewList.get(i)));
            }
            for(HzResourceGroupView item : resourceGroupViewList) {
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
            }

            Set<String> jutiSet = new HashSet<>();   // 视图中的具体资源组编号 F
            Map<String, HzResourceGroupView> jutiSetMap = new HashMap<>();  // 视图中的组编号对应的
            for(HzResourceGroupView t : resourceGroupViewList) {
                if(t.getResourceType().equals(1)) {
                    jutiSet.add(t.getResourceGroupNO().trim() + "(" + t.getWorkCenter().trim() + ")");
                    jutiSetMap.put(t.getResourceGroupNO().trim() + "(" + t.getWorkCenter().trim() + ")", t);
                }else{
                    jutiSet.add(t.getResourceGroupNO().trim());
                    jutiSetMap.put(t.getResourceGroupNO().trim(), t);
                }
                if(StringUtils.isNotEmpty(t.getGroupNo().trim())) {
                    groupNoSet.add(t.getGroupNo().trim());
                    groupNoMap.put(t.getGroupNo().trim(), t.getResourceType());
                    groupNoNameMap.put(t.getGroupNo().trim(), t.getGroupName().trim());
                }
            }
            List<Resourcegroup> groupList = resourcegroupService.list();
            Set<String> noSet = new HashSet<>();    // 所有现在表中已存在的 no
            Map<String, Resourcegroup> allItemMap = new HashMap<>();  // 所有Item和实体类的映射
            for(Resourcegroup t : groupList) {
                noSet.add(t.getResourceGroupNO().trim());
                allItemMap.put(t.getResourceGroupNO().trim(), t);
            }
            Set<String> cp = new HashSet<>(groupNoSet);
            cp.removeAll(noSet);
            if(cp.size() > 0) {   // 如果有不一样的，就是需要创建 M     CT-HD-3462 面板下盖
                for(String t : cp) {
                    if(StringUtils.isEmpty(t)) continue;
                    Resourcegroup resourcegroup = new Resourcegroup();
                    resourcegroup.setType("M");  resourcegroup.setResourceGroupParentId(groupNoMap.get(t));
                    resourcegroup.setResourceGroupNO(t); resourcegroup.setResourceGroupName(groupNoNameMap.get(t));
                    resourcegroupService.save(resourcegroup);
//                  System.out.println("已保存的resourcegroup: " + resourcegroup);
                    if(resourcegroup.getResourceGroupId() == null) throw new CustomException("500", "resourcegroup M插入后没有给ID");
                    allItemMap.put(t.trim(), resourcegroup);  // ???
                }
            }
            cp = new HashSet<>(jutiSet);
            cp.removeAll(noSet);
            if(cp.size() > 0) {
                Resourcegroup one = resourcegroupMapper.selectOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, "N-IPA100-01"));
                System.out.println(one);
                for(String t : cp) {
                    HzResourceGroupView view = jutiSetMap.get(t);
                    Resourcegroup resourcegroup = new Resourcegroup();
                    resourcegroup.setType("F");
                    if(StringUtils.isNotEmpty(view.getGroupNo())) {
//                        System.out.println("view.getGroupNo = ^" + view.getGroupNo() + "^");
                        Resourcegroup resourcegroup1 = allItemMap.get(view.getGroupNo().trim());
//                        if(resourcegroup1 == null) System.out.println("resourcegroup1 is null");
                        Integer i = resourcegroup1.getResourceGroupId();
//                        if(i == null) System.out.println("iiii is null");
                        resourcegroup.setResourceGroupParentId(i);
                    } else resourcegroup.setResourceGroupParentId(view.getResourceType());
                    resourcegroup.setResourceGroupNO(t);
                    resourcegroup.setResourceGroupName(view.getResourceGroupName().trim());
                    resourcegroupService.save(resourcegroup);
                    if(resourcegroup.getResourceGroupId() == null) throw new CustomException("500", "resourcegroup F插入后没有给ID");
                    allItemMap.put(resourcegroup.getResourceGroupNO(), resourcegroup);
                    Resource resource = new Resource();
                    resource.setResourceType(view.getResourceType());
                    resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
                    resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
                    resource.setDeviceid(resourcegroup.getResourceGroupNO());
                    resource.setDevicename(resourcegroup.getResourceGroupName());
                    resource.setWorkCenter(view.getWorkCenter());
                    resource.setMouldDrawNo(view.getMouldDrawNo());
                    String status = "";
                    switch (view.getSTATE()) {
                        case "启用": status = MouldStatusEnum.XianZhi.getValue(); break;
                        case "已停用": status = MouldStatusEnum.YiTingYong.getValue(); break;
                        case "已审核": status = MouldStatusEnum.YiShenHe.getValue(); break;
                        case "开模中": status = MouldStatusEnum.KaiMoZhong.getValue(); break;
                        case "已报废": status = MouldStatusEnum.YiBaoFei.getValue(); break;
                        case "已作废": status = MouldStatusEnum.YiZuoFei.getValue(); break;
                        case "未审核": status = MouldStatusEnum.WeiShenHe.getValue(); break;
                    }
                    resource.setStatus(status);
                    resource.setDevicestatus(view.getSTATE());
                    resourceService.save(resource);
                }
            }

            cp = new HashSet<>(noSet);
            cp.retainAll(jutiSet);
            for(String t : cp) {        // 资源组修改  资源表修改

                HzResourceGroupView view = jutiSetMap.get(t);
                Resourcegroup groupInfo = null;
                if(StringUtils.isNotEmpty(view.getGroupNo())) groupInfo = allItemMap.get(view.getGroupNo().trim());   // 组编号

                Resourcegroup item = new Resourcegroup();
                item.setType(view.getType());
                item.setResourceGroupName(view.getResourceGroupName());
                item.setResourceGroupParentId(groupInfo == null ? view.getResourceType() : groupInfo.getResourceGroupId());
                resourcegroupMapper.update(item, new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, t));

                Resource resource = new Resource();
                resource.setResourceType(view.getResourceType());
                resource.setResourceGroupId(groupInfo == null ? view.getResourceType() : groupInfo.getResourceGroupId());
                resource.setDevicename(view.getResourceGroupName());
                resource.setWorkCenter(view.getWorkCenter());
//                String status = "";
//                switch (view.getSTATE()) {
//                    case "启用": status = MouldStatusEnum.XianZhi.getValue(); break;
//                    case "已停用": status = MouldStatusEnum.YiTingYong.getValue(); break;
//                    case "已审核": status = MouldStatusEnum.YiShenHe.getValue(); break;
//                    case "开模中": status = MouldStatusEnum.KaiMoZhong.getValue(); break;
//                    case "已报废": status = MouldStatusEnum.YiBaoFei.getValue(); break;
//                    case "已作废": status = MouldStatusEnum.YiZuoFei.getValue(); break;
//                    case "未审核": status = MouldStatusEnum.WeiShenHe.getValue(); break;
//                }
                resource.setDevicestatus(view.getSTATE()); // 不能更新status, 只能更新devicestatus
                resource.setMouldDrawNo(view.getMouldDrawNo());
                resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, t));
            }

            // 删除掉，VIEW中不存在的内容
            List<String> viewNo = hzViewSyncMapper.hzResourceGroupListOnlyNO();
            Set<String> viewAllNo = new HashSet<>();
            // 需要先将编号进行繁体转简体
            for(String t : viewNo) {
                if(ZhTwConverterUtil.containsTraditional(t.trim())) {
                    t = ZhConvertBootstrap.newInstance().segment(Segments.chars())
                            .toSimple(t.trim());
                }
                viewAllNo.add(t.trim());
            }
            // 最外面四个的值，不能被删除
            viewAllNo.add("设备");
            viewAllNo.add("生产线");
            viewAllNo.add("模具");
            viewAllNo.add("工装");
//            System.out.println("allNo = " + allNo.size());
//            System.out.println("viewAllNo = " + viewAllNo.size());
            cp = new HashSet<>(noSet);
            cp.removeAll(viewAllNo);
//            System.out.println("cp = " + cp.size());
            List<Viewsynclog> viewsynclogList = new ArrayList<>();
            System.out.println("视图中的数量: " + viewAllNo.size());
            System.out.println("同步后的数量: " + noSet.size());
            System.out.println("需要删除的数量: " + cp.size());
            for(String t : cp) {  // 删除我们这边有的，VIEW中没有的 具体资源

                // TODO 如果有后置单据，则不能删除。把机器的状态改成 不可用

                // 删除的日志，记一下
                Viewsynclog viewsynclog = new Viewsynclog("resourcegroup", "DELETE", "删除编号:" + t, TimeUtils.getFullNowTime());
                viewsynclogList.add(viewsynclog);
                resourcegroupMapper.delete(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, t));
                resourceMapper.delete(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, t));
                productprocessresourceMapper.delNoResourcegroupId();
            }
            viewsynclogService.saveBatch(viewsynclogList);
            if(resourcegroupLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("resourcegroup");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "resourcegroup"));
            }

        }
        /**
         * resource  VIEW中只有模具的内容
         */
        List<HzResourceView> resourceViewList = null;
        Tablesynclog resourceLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "resource"));
        if(resourceLog == null || StringUtils.isEmpty(resourceLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            resourceViewList = hzViewSyncMapper.hzResourceViewList(null);
        }else{
            resourceViewList = hzViewSyncMapper.hzResourceViewList(resourceLog.getLastsynctime());
        }
        if(resourceViewList != null && resourceViewList.size() > 0) {
            String lastTime = "";
            for(int i = 0; i < resourceViewList.size(); i++) {
                resourceViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(resourceViewList.get(i)));
            }
            Set<String> resourceViewSet = new HashSet<>();
            Map<String, HzResourceView> resourceViewMap = new HashMap<>();

            List<Resourcegroup> resourcegroupList = resourcegroupService.list();
            Map<String, Resourcegroup> resourcegroupMap = new HashMap<>();
            for(Resourcegroup t : resourcegroupList) {
                resourcegroupMap.put(t.getResourceGroupNO().trim(), t);
            }

            for(HzResourceView item : resourceViewList) {
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
                resourceViewSet.add(item.getDeviceId().trim());
                resourceViewMap.put(item.getDeviceId().trim(), item);
            }
            List<Resource> resourceList = resourceService.list();
            Set<String> originResourceSet = new HashSet<>();
            Map<String, Resource> originResourceMap = new HashMap<>();
            for(Resource item : resourceList) {
                originResourceSet.add(item.getDeviceid().trim());
                originResourceMap.put(item.getDeviceid().trim(), item);
            }
            Set<String> cp = new HashSet<>(resourceViewSet);
            cp.removeAll(originResourceSet);
            List<Resource> insResourceList = new ArrayList<>();
            for(String t : cp) {
                HzResourceView view = resourceViewMap.get(t);
                Resourcegroup resourcegroup = resourcegroupMap.get(t);
                Resource resource = new Resource();
                resource.setResourceType(Integer.parseInt(view.getDeviceType()));   resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
                resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
                resource.setDeviceid(view.getDeviceId());  resource.setDevicename(view.getDeviceName());
                resource.setMouldDrawNo(view.getMouldDrawNo());  resource.setFixedassetid(view.getFixedAssetId());
                resource.setExfactorydate(view.getExfactoryDate());  resource.setRemark(view.getRemark());
                String status = "";
                switch (view.getDeviceStatus()) {
                    case "启用": status = MouldStatusEnum.XianZhi.getValue(); break;
                    case "已停用": status = MouldStatusEnum.YiTingYong.getValue(); break;
                    case "已审核": status = MouldStatusEnum.YiShenHe.getValue(); break;
                    case "开模中": status = MouldStatusEnum.KaiMoZhong.getValue(); break;
                    case "已报废": status = MouldStatusEnum.YiBaoFei.getValue(); break;
                    case "已作废": status = MouldStatusEnum.YiZuoFei.getValue(); break;
                    case "未审核": status = MouldStatusEnum.WeiShenHe.getValue(); break;
                }
                resource.setStatus(status);
                resource.setDevicestatus(view.getDeviceStatus());
                resource.setCavityNumber(view.getCavityNumber());  resource.setCavitySpecifications(view.getCavitySpecifications());
                resource.setDesignLife(view.getDesignLife());  resource.setUsedNumber(view.getUsedNumber());
                resource.setStorageLocation(view.getStorageLocation());

                resource.setFactoryMouldDrawingNumber(view.getFactoryMouldDrawingNumber());
                resource.setFactoryMouldDrawingVersion(view.getFactoryMouldDrawingVersion());
                resource.setCustomMouldDrawingNumber(view.getCustomMouldDrawingNumber());
                resource.setMouldType(view.getMouldType());
                resource.setWeight(view.getWeight());
                resource.setNameplateNumber(view.getNameplateNumber());
                resource.setOwnerName(view.getOwnerName());
                resource.setAssetFactory(view.getAssetFactory());
                resource.setLocationNumber(view.getLocationNumber());
                resource.setLocationName(view.getLocationName());
                resource.setModelStorageLocation(view.getModelStorageLocation());
                resource.setModelAdditionalInformation(view.getModelAdditionalInformation());
                resource.setMouldOpenOrderDay(view.getMouldOpenOrderDay());
                resource.setMouldOpenDay(view.getMouldOpenDay());
                resource.setExpectedCompletionDateOfMouldOpen(view.getExpectedCompletionDateOfMouldOpen());
                resource.setWarrantyExpirationDate(view.getWarrantyExpirationDate());
                resource.setInjectionMachineOunces(view.getInjectionMachineOunces());
                resource.setMachinePipeDiameter(view.getMachinePipeDiameter());
                resource.setSafeDesignLife(view.getSafeDesignLife());

                resource.setScrapDate(view.getScrapDate());
                resource.setScrapReason(view.getScrapReason());
                resource.setDeactivationDate(view.getDeactivationDate());
                resource.setDeactivationReason(view.getDeactivationReason());
                resource.setReactivationDay(view.getReactivationDay());
                resource.setInvMaterial(view.getInvMaterial());
                insResourceList.add(resource);
            }
            resourceService.saveBatch(insResourceList);   // 批量插入
            // 批量更新
            cp = new HashSet<>(originResourceSet);
            cp.retainAll(resourceViewSet);
            for(String t : cp) {
                HzResourceView view = resourceViewMap.get(t);
                Resourcegroup resourcegroup = resourcegroupMap.get(t);
                Resource resource = new Resource();
                resource.setResourceType(Integer.parseInt(view.getDeviceType()));
                resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
                resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
                resource.setDevicename(view.getDeviceName());
                resource.setDevicestatus(view.getDeviceStatus());
                resource.setMouldDrawNo(view.getMouldDrawNo());  resource.setFixedassetid(view.getFixedAssetId());
                resource.setExfactorydate(view.getExfactoryDate());  resource.setRemark(view.getRemark());
                resource.setDevicestatus(view.getDeviceStatus());
                resource.setCavityNumber(view.getCavityNumber());
                resource.setCavitySpecifications(view.getCavitySpecifications());
                resource.setDesignLife(view.getDesignLife());
                resource.setStorageLocation(view.getStorageLocation());
//                resource.setUsedNumber(view.getUsedNumber());


                resource.setFactoryMouldDrawingNumber(view.getFactoryMouldDrawingNumber());
                resource.setFactoryMouldDrawingVersion(view.getFactoryMouldDrawingVersion());
                resource.setCustomMouldDrawingNumber(view.getCustomMouldDrawingNumber());
                resource.setMouldType(view.getMouldType());
                resource.setWeight(view.getWeight());
                resource.setNameplateNumber(view.getNameplateNumber());
                resource.setOwnerName(view.getOwnerName());
                resource.setAssetFactory(view.getAssetFactory());
                resource.setLocationNumber(view.getLocationNumber());
                resource.setLocationName(view.getLocationName());
                resource.setModelStorageLocation(view.getModelStorageLocation());
                resource.setModelAdditionalInformation(view.getModelAdditionalInformation());
                resource.setMouldOpenOrderDay(view.getMouldOpenOrderDay());
                resource.setMouldOpenDay(view.getMouldOpenDay());
                resource.setExpectedCompletionDateOfMouldOpen(view.getExpectedCompletionDateOfMouldOpen());
                resource.setWarrantyExpirationDate(view.getWarrantyExpirationDate());
                resource.setInjectionMachineOunces(view.getInjectionMachineOunces());
                resource.setMachinePipeDiameter(view.getMachinePipeDiameter());
                resource.setSafeDesignLife(view.getSafeDesignLife());

                resource.setScrapDate(view.getScrapDate());
                resource.setScrapReason(view.getScrapReason());
                resource.setDeactivationDate(view.getDeactivationDate());
                resource.setDeactivationReason(view.getDeactivationReason());
                resource.setReactivationDay(view.getReactivationDay());
                resource.setInvMaterial(view.getInvMaterial());
                resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, t));
            }
            if(resourceLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("resource");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "resource"));
            }
        }
        System.out.println("resourceGroup_ResourceViewSync end.........");
//        // 更新PPR
//        List<HzResourceGroupView> hzPPRViewList = hzViewSyncMapper.hzPPRViewList();
//        List<Productprocessresource> pprList = productprocessresourceService.list();
//        for(HzResourceGroupView t : hzPPRViewList) {
//
//        }
    }
}
